# exceptions.py
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import ORJSONResponse


def register_exception_handlers(app):
    """
    为 FastAPI 应用注册全局异常处理器。
    """

    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler_localized(request: Request, exc: RequestValidationError):
        """
        定义全局异常捕获
        """
        errors = exc.errors()
        simplified = []
        for err in errors:
            loc = err.get("loc", [])
            field = loc[-1] if loc else "field"
            err_type = err.get("type", "")
            ctx = err.get("ctx", {}) or {}
            # 根据 err_type 进行本地化
            if err_type == "value_error.missing":
                # 缺少字段
                msg = "字段必填"
            elif err_type == "type_error.integer":
                msg = "必须是整数"
            elif err_type == "string_too_short":
                min_len = ctx.get("min_length")
                msg = f"长度至少{min_len}个字符" if min_len is not None else err.get("msg")
            elif err_type == "string_too_long":
                max_len = ctx.get("max_length")
                msg = f"长度不能超过{max_len}个字符" if max_len is not None else err.get("msg")
            else:
                # 其他类型，直接使用默认 msg
                msg = err.get("msg", "")
            simplified.append({"field": field, "message": msg})
        # 你可以只返回第一条，或返回数组；这里返回数组示例
        return ORJSONResponse(
            status_code=422,
            content={"code": 422, "message": simplified}
        )
